/*********************************************************************************
 *      Copyright:  (C) 2015 NO
 *                  All rights reserved.
 *
 *       Filename:  average.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2015年09月22日)
 *         Author:  fulinux <fulinux@sina.com>
 *      ChangeLog:  1, Release initial version on "2015年09月22日 22时54分00秒"
 *                 
 ********************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>

lua_State *L;

int lua_average(int arr[], int n)
{
    int sum;
    int data;
    int i;

    lua_getglobal(L, "average");
    for(i = 0; i < n; i++){
        lua_pushnumber(L, arr[i]);
    }
    lua_pushnumber(L, n);
    lua_call(L, n + 1, 1);
    sum = (int)lua_tointeger(L, -1);
    lua_pop(L, 1);
    return sum;
}

int main(int argc, char **argv)
{
    int sum;
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    L = lua_open();
    luaL_openlibs(L);
    luaL_dofile(L, "average.lua");
    sum = lua_average(arr, 9);
    printf("Result is %d\n", sum);
    lua_close(L);
    return 0;
}
